package mq.rpc;

import com.rabbitmq.client.*;
import mq.Constants.Constants;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeoutException;

/**
 * @author: Themberfue
 * @date: 2025/4/27 21:01
 * @description:
 */
public class RPCClient {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        // TODO 1. 建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constants.HOST);
        connectionFactory.setPort(Constants.PORT);
        connectionFactory.setUsername(Constants.USER_NAME);
        connectionFactory.setPassword(Constants.PASSWORD);
        connectionFactory.setVirtualHost(Constants.VIRTUAL_HOST);
        Connection connection = connectionFactory.newConnection();

        // TODO 2. 开启隧道
        Channel channel = connection.createChannel();

        // TODO 2.1 声明队列
        channel.queueDeclare(Constants.RPC_RESPONSE_QUEUE, true, false, false, null);
        channel.queueDeclare(Constants.RPC_REQUEST_QUEUE, true, false, false, null);

        // TODO 3. 发送请求
        String correlationId = UUID.randomUUID().toString();
        AMQP.BasicProperties properties = new AMQP.BasicProperties().builder()
                .correlationId(correlationId) // ? 唯一标识，标识接收该 ID 的响应
                .replyTo(Constants.RPC_RESPONSE_QUEUE)
                .build();
        String msg = "hello RPC mode~：" + correlationId;
        channel.basicPublish("", Constants.RPC_REQUEST_QUEUE, properties, msg.getBytes(StandardCharsets.UTF_8));

        // TODO 4. 接收响应
        BlockingQueue<String> queue = new LinkedBlockingQueue<>(1);
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String resp = new String(body);
                System.out.println("接收到回调消息：" + resp);
                if (properties.getCorrelationId().equals(correlationId)) {
                    queue.offer(resp);
                }
            }
        };
        channel.basicConsume(Constants.RPC_RESPONSE_QUEUE, true, consumer);

        String res = queue.take();// ! 若没有对应的消息，程序会在这里阻塞
        System.out.println("[RPC Client接收到符合 ID 的消息]：" + res);
    }
}
